package com.kly.cashmall.services.gson;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.kly.cashmall.utils.function.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author
 * @version $Id$
 * @since 2018/9/18 21:11
 */
final class CustomResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private TypeAdapter<T> adapter;
    private Type mType;

    CustomResponseConverter(Gson gson, TypeAdapter<T> mAdapter, Type mType) {
        this.gson = gson;
        this.adapter = mAdapter;
        this.mType = mType;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        try {
            String body = value.string();
            JSONObject json = new JSONObject(body);

            int code = json.getInt("code");
            if (code == 0) {
                if (json.has("data") && !json.getString("data").equals("null")){
                    return gson.fromJson(json.getString("data"), mType);
                }else {
                    return gson.fromJson(body, mType);
                }
            } else {
                if (code != 90000){
                    ToastUtil.showToast(json.getString("msg"));
                }
                throw new RuntimeException(json.getString("msg"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            value.close();
        }
    }
}